package com.godofball.medtrack.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.godofball.medtrack.common.Result;
import com.godofball.medtrack.pojo.Type;
import com.godofball.medtrack.service.TypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/type")
@Slf4j
public class TypeController {

    @Autowired
    private TypeService typeService;

@GetMapping("page")
public Result<Page> page(@RequestParam(value = "page",defaultValue = "1")Integer page,
                         @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize){
    log.info("page:{},pageSize:{}",page,pageSize);

    Page<Type> typePage = new Page<>(page,pageSize);

    LambdaQueryWrapper<Type> typeLambdaQueryWrapper = new LambdaQueryWrapper<>();
    typeLambdaQueryWrapper.orderByDesc(Type::getSort).orderByDesc(Type::getCreateTime);

    typeService.page(typePage,typeLambdaQueryWrapper);

    return Result.success(typePage);
}

@PostMapping
public Result<String> add(@RequestBody Type type){
    log.info(type.toString());
    typeService.save(type);
    return Result.success("ok");
}

    @PutMapping
    public Result<String> update(@RequestBody Type type){
        log.info(type.toString());
        typeService.updateById(type);
        return Result.success("ok");
    }

    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable("id") Long id){
        log.info("delete id:{}",id);
        typeService.removeById(id);
        return Result.success("ok");
    }

    @GetMapping("/list")
    public Result<List<Type>> list(){
        LambdaQueryWrapper<Type> typeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        typeLambdaQueryWrapper.orderByDesc(Type::getSort);
        typeLambdaQueryWrapper.orderByDesc(Type::getUpdateTime);
        List<Type> list = typeService.list();
        return Result.success(list);
    }

    @GetMapping("/{id}")
    public Result<Type> getById(@PathVariable("id") Long id){
        Type type = typeService.getById(id);
        return Result.success(type);
    }

}
